package com.wrh.draw;

import com.wrh.draw.layer.BoundaryLayer;
import com.wrh.draw.layer.LonLatLayer;
import com.wrh.draw.layer.MarkerLayer;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;

/**
 * @author wrh
 */
public class ImagePanel {

    protected BufferedImage image = null;
    protected Graphics2D g = null;

    private ImagePanel(int imgWidth, int imgHeight) {
        this.image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_4BYTE_ABGR);
        this.g = this.image.createGraphics();
    }

    public static ImagePanel createImagePanel(int imgWidth, int imgHeight) {
        return new ImagePanel(imgWidth, imgHeight);
    }

    public void dispose() {
        this.g.dispose();
    }

    public BufferedImage getImage() {
        return image;
    }

    public ImagePanel setImgBackground(Color color) {
        Graphics2D g2d = (Graphics2D) this.g.create();
        g2d.setBackground(color);
        g2d.clearRect(0, 0, this.image.getWidth(), this.image.getHeight());
        g2d.dispose();
        return this;
    }

    public ImagePanel addShape(Shape shape, Graphics2DStyle graphics2dStyle) {
        Graphics2D g2d = (Graphics2D) this.g.create();
        graphics2dStyle.setStyle(g2d);
        g2d.draw(shape);
        g2d.dispose();
        return this;
    }

    public ImagePanel addLonLatPanel(LonLatPanel lonLatPanel) {
        LonLatConverter lonLatConverter = new LonLatConverter(this.image.getWidth(), this.image.getHeight(),
                lonLatPanel.getLonMin(), lonLatPanel.getLonMax(), lonLatPanel.getLatMin(), lonLatPanel.getLatMax());
        List<LonLatLayer> lonLatLayers = lonLatPanel.getLonLatLayers();
        lonLatLayers.forEach(lonLatLayer -> {
            Graphics2D g2d = (Graphics2D) this.g.create();
            if (lonLatLayer instanceof MarkerLayer) {
                Point point = lonLatConverter.lonLatToPoint(((MarkerLayer) lonLatLayer).getLonLat());
                ((MarkerLayer) lonLatLayer).draw(g2d, point);
            } else if (lonLatLayer instanceof BoundaryLayer) {
                ((BoundaryLayer) lonLatLayer).draw(g2d, lonLatConverter);
            }
            g2d.dispose();
        });
        return this;
    }
}
